package com.mbigger.synchronize;

/**
 * 类锁的第一种形式，static形式
 * 
 * @author mbigg
 *
 */
public class SynchronizedCodeblock implements Runnable {
    static SynchronizedCodeblock instance1 = new SynchronizedCodeblock();
    // static SynchronizedCodeblock instance2 = new SynchronizedCodeblock();

    static int i = 0;

    public static void main(String[] args) {
        Thread t1 = new Thread(instance1);
        Thread t2 = new Thread(instance1);
        t1.start();
        t2.start();
        while (t1.isAlive() || t2.isAlive()) {
        }
        System.err.println(i);
        System.err.println("finished!");
    }

    public void run() {
        method();
    }

    public void method() {

        // synchronized(SynchronizedCodeblock.class) {
        synchronized (this) {
            System.err.println("我是同步块内代码，我叫：" + Thread.currentThread().getName());
            for (int j = 0; j < 10000; j++) {
                System.err.println(Thread.currentThread().getName() + ": " + i++);
            }
            System.err.println("同步块内代码运行结束，我叫：" + Thread.currentThread().getName());

        }

        System.err.println("我是同步块外代码，我叫：" + Thread.currentThread().getName());
        for (int j = 0; j < 100000; j++) {
            System.err.println(Thread.currentThread().getName() + ": " + i++);
        }
        System.err.println("同步块外代码运行结束，我叫：" + Thread.currentThread().getName());
    }

}
